package inc.zhugastrov.sellerform;

import inc.zhugastrov.users.Account;
import inc.zhugastrov.users.Position;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import static inc.zhugastrov.dbactions.DBActions.putToWherehouse;
import static inc.zhugastrov.dbactions.DBActions.addItem;
import static inc.zhugastrov.dbactions.DBActions.putToBasket;
import static inc.zhugastrov.ui.AuthorizationForm.getAuthorizedUser;
import static inc.zhugastrov.dbactions.DBActions.fillItems;
import javax.swing.Box.Filler;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableRowSorter;

public class MainPanel extends JPanel implements ActionListener {
	private static MainPanel instance;
	private JTable catalog;
	private ItemsTableModel model = new ItemsTableModel();
	private JScrollPane scrollPane;
	private JButton addToBasketButton;
	private JButton orderMore;
	private JTextField filterText;
	private TableRowSorter sorter;
	private JPopupMenu popupMenu;
	private JMenuItem menuItem;
	private Account authorizedUser = getAuthorizedUser();

	private MainPanel() {
		super();
		setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
		init();
//
		addItem(new Item(1L));
		addItem(new Item(2L));
		addItem(new Item(3L));
		addItem(new Item(4L));
		addItem(new Item(5L));
		addItem(new Item(6L));

	}

	public void addToItem(Item item) {
		model.addRow(item);
	}

	public ItemsTableModel getModel() {
		return model;
	}

	public static MainPanel getInstance() {
		if (instance == null)
			instance = new MainPanel();
		return instance;
	}

	private void init() {

		popupMenu = new JPopupMenu();
		menuItem = new JMenuItem("Add to Basket");
		menuItem.addActionListener(this);
		popupMenu.add(menuItem);

		catalog = new JTable();
		catalog.setModel(model);
		catalog.getTableHeader().setReorderingAllowed(false);
		catalog.setFocusable(false);
		catalog.setSelectionMode(0);
		catalog.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				if ((catalog.getSelectedRow() != -1) && (e.isPopupTrigger()))
					popupMenu.show(e.getComponent(), e.getX(), e.getY());

			}

			@Override
			public void mouseReleased(MouseEvent e) {
				if ((catalog.getSelectedRow() != -1) && (e.isPopupTrigger()))
					popupMenu.show(e.getComponent(), e.getX(), e.getY());
			}

		});
		sorter = new TableRowSorter<ItemsTableModel>(model);
		catalog.setRowSorter(sorter);
		scrollPane = new JScrollPane(catalog);
		catalog.setPreferredScrollableViewportSize(new java.awt.Dimension(500,
				300));
		add(scrollPane);
		addToBasketButton = new JButton("Add to basket");
		addToBasketButton.setSize(20, 50);
		addToBasketButton.addActionListener(this);
		if (authorizedUser.getPosition() == Position.SELLER
				|| authorizedUser.getPosition() == "SUPER")
			add(addToBasketButton);
		orderMore = new JButton("Order from wherehouse");
		orderMore.setSize(20, 50);
		orderMore.setActionCommand("orderMore");
		orderMore.addActionListener(this);
		if (authorizedUser.getPosition() == Position.MANAGER
				|| authorizedUser.getPosition() == "SUPER")
			add(orderMore);
		
		
		filterText = new JTextField();
		JLabel l1 = new JLabel("Filter Text:", SwingConstants.TRAILING);
		add(l1);
		l1.setLabelFor(filterText);
		filterText.setSize(50, 20);

		add(filterText);
		filterText.getDocument().addDocumentListener(new DocumentListener() {
			public void changedUpdate(DocumentEvent e) {
				newFilter();
			}

			public void insertUpdate(DocumentEvent e) {
				newFilter();
			}

			public void removeUpdate(DocumentEvent e) {
				newFilter();
			}
		});

	}

	private void newFilter() {
		RowFilter<ItemsTableModel, Object> rf = null;
		// If current expression doesn't parse, don't update.
		try {
			int[] ind = { 0, 1, 2 };

			rf = RowFilter.regexFilter("(?i)" + filterText.getText(), ind);
		} catch (java.util.regex.PatternSyntaxException e) {
			return;
		}
		sorter.setRowFilter(rf);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		try {
		if(e.getActionCommand().equals("orderMore")){
			String choise = JOptionPane.showInputDialog(this,
					"How many items?", "Amount", JOptionPane.PLAIN_MESSAGE);
			if ((choise.equals("")) || (choise == null))
				return;
			int amount = Integer.valueOf(choise);
			WherehousePane whp = WherehousePane.getInstance();
			Item item = (Item) model.getRow(catalog
					.convertRowIndexToModel(catalog.getSelectedRow()));
			if ((amount <= 10) && amount > 0) {
				Item toBasket = (Item) item.clone();
				toBasket.setAmountInStore(amount);
				putToWherehouse(toBasket);
				whp.addToWherehouse(new Wherehouse(toBasket));
				return;
			}
			else if (amount <= 0) {
				JOptionPane.showMessageDialog(this,
						"Why do you want to add nothing, ga?", "Error",
						JOptionPane.ERROR_MESSAGE);
				return;
			}
			
			
		}
		if (catalog.getSelectedRow() == -1) {
			JOptionPane.showMessageDialog(this,
					"No orders selected, don't you see this?", "Error",
					JOptionPane.ERROR_MESSAGE);

			return;
		}
			BasketPanel basket = BasketPanel.getInstance();
			String choise = JOptionPane.showInputDialog(this,
					"How many items?", "Amount", JOptionPane.PLAIN_MESSAGE);
			if ((choise.equals("")) || (choise == null))
				return;
			int amount = Integer.valueOf(choise);
			Item item = (Item) model.getRow(catalog
					.convertRowIndexToModel(catalog.getSelectedRow()));
			if ((amount <= item.getAmountInStore()) && amount > 0) {
				model.changeAmount(item.getAmountInStore() - amount, catalog
						.convertRowIndexToModel(catalog.getSelectedRow()));
				catalog.updateUI();
				Item toBasket = (Item) item.clone();
				toBasket.setAmountInStore(amount);
				putToBasket(toBasket);
				basket.addToBasket(toBasket);
			} else if (amount <= 0) {
				JOptionPane.showMessageDialog(this,
						"Why do you want to add nothing, ga?", "Error",
						JOptionPane.ERROR_MESSAGE);
				return;
			} else {
				JOptionPane.showMessageDialog(this,
						"We don't have as many as you wish=(", "Error",
						JOptionPane.ERROR_MESSAGE);
				return;
			}

		} catch (NumberFormatException exception) {

			JOptionPane
					.showMessageDialog(
							this,
							"Oooopsss, you enter some shit in input dialog, try again, man",
							"Error", JOptionPane.ERROR_MESSAGE);
		} catch (CloneNotSupportedException exception) {
			System.out.println("Shit happend!!!=(((");
		}

	}
}